/**
 * <b>项目名：</b>oasis-service<br/>
 * <b>包名：</b>com.bookdao.oasis.common.framework.dao<br/>
 * <b>文件名：</b>PageQueryInterceptor.java<br/>
 * <b>描述：</b><br/>
 * <b>版本信息：</b>v1.0.0<br/>
 * <b>日期：</b>2015年10月26日-上午9:03:40<br/>
 * <b>Copyright (c)</b> 2015智道@版权所有<br/>
 */

package com.bookdao.oasis.common.framework.dao;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.RowBounds;

/**
 * <b>类名称：</b>PageQueryInterceptor <br/>
 * <b>类描述：</b><br/>
 * <b>创建人：</b>zhanghj<br/>
 * <b>修改人：</b><br/>
 * <b>修改时间：</b>2015年10月26日 上午9:03:40<br/>
 * <b>修改备注：</b><br/>
 * <b>版本信息：</b>v1.0.0<br/>
 */
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class,Integer.class }) })
public class PageQueryInterceptor implements Interceptor {
	protected static final String SQL_END_DELIMITER = ";";
	public static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
	public static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
	
	public static final ReflectorFactory DEFAULT_REFLECTOR_FACTORY = new DefaultReflectorFactory();
	/* (non-Javadoc)
	 * @see org.apache.ibatis.plugin.Interceptor#intercept(org.apache.ibatis.plugin.Invocation)
	 */
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
        MetaObject metaStatementHandler = MetaObject.forObject(statementHandler,DEFAULT_OBJECT_FACTORY,DEFAULT_OBJECT_WRAPPER_FACTORY,DEFAULT_REFLECTOR_FACTORY);
        RowBounds rowBounds = (RowBounds)metaStatementHandler.getValue("delegate.rowBounds");
        if(rowBounds ==null|| rowBounds == RowBounds.DEFAULT){
            return invocation.proceed();
        }
        String originalSql = (String)metaStatementHandler.getValue("delegate.boundSql.sql");
        metaStatementHandler.setValue("delegate.boundSql.sql",getLimitString(originalSql, rowBounds.getOffset(), rowBounds.getLimit()) );
        metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
        metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
        return invocation.proceed();
	}

	/* (non-Javadoc)
	 * @see org.apache.ibatis.plugin.Interceptor#plugin(java.lang.Object)
	 */
	@Override
	public Object plugin(Object target) {
       return Plugin.wrap(target, this);
	}

	/* (non-Javadoc)
	 * @see org.apache.ibatis.plugin.Interceptor#setProperties(java.util.Properties)
	 */
	@Override
	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub

	}
	/**
	 * 
	 * @Title getLimitString
	 * @Description 拼接分页SQL语句
	 * @param sql  源SQL语句
	 * @param offset 从第几条数据开始取值
	 * @param limit 取多少条数据
	 * @return 
	 * String 带分页关键字的SQL语句
	 * @author zhanghj
	 * @date 2015年10月26日-上午9:12:54
	 * @update 
	 * @throws
	 */
	public String getLimitString(String sql, int offset, int limit) {  
        sql = trim(sql);  
        StringBuffer sb = new StringBuffer(sql.length() + 20);  
        sb.append(sql);  
        if (offset > 0) {  
            sb.append(" limit ").append(offset).append(',').append(limit)  
                    .append(SQL_END_DELIMITER);  
        } else {  
            sb.append(" limit ").append(limit).append(SQL_END_DELIMITER);  
        }  
        return sb.toString();  
    }  
	/**
	 * 
	 * @Title trim
	 * @Description 剔除SQL语句前后空格以及结尾的分号
	 * @param sql
	 * @return 
	 * String 
	 * @author zhanghj
	 * @date 2015年10月26日-上午9:16:25
	 * @update 
	 * @throws
	 */
    private String trim(String sql) {  
        sql = sql.trim();  
        if (sql.endsWith(SQL_END_DELIMITER)) {  
            sql = sql.substring(0, sql.length() - 1 
                    - SQL_END_DELIMITER.length());  
        }  
        return sql;  
    }  

}
